import React from 'react';
import {App, Card, Table} from 'antd';
import { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import { AsyncThunk, AsyncThunkConfig } from '@reduxjs/toolkit/dist/createAsyncThunk';
import { Link } from 'react-router-dom';
import TableToolbar from './TableToolbar';
import LogFactory from 'log/LogFactory';
import JsonResult from 'http/JsonResult';
import { PagingData, PagingResult } from 'type/Page';
import BaseEntity from 'type/entity';
import { StatePagingType } from 'storage/redux';
import {useAppDispatch, useAppSelector} from 'storage/redux/hook';
import RequestStatus from 'storage/redux/RequestStatus';
import {StoreKeys} from "../../storage/redux/store";

/**
 * table增强组件属性约束接口
 * @param T 实体类型
 */
export interface TableEnhanceProps<T extends BaseEntity> {
    /** 表格增强组件的标题 */
    title?: string,
    /** 后退链接显示文件信息,默认为backup */
    backupText?: string,
    /** 后退链接跳转的地址,默认为.. */
    backupUrl?: string,
    /** 表格的列信息 */
    columns: ColumnsType<T>
    /** 表格数据 */
    dataSource?: T[]
    /** 表格加载状态 */
    loading?: boolean,
    /** 刷新按钮的回调,当用户配置了reduxState和pageAsyncAction,并且没有配置刷新按钮函数的时候,默认的刷新会执行pageAsyncAction */
    refresh?: () => void
    /** 新建数据按钮的跳转地址: 默认为add */
    addUrl?: string,
    /** redux的状态信息,当使用了这个值的时候dataSource,和loading不需要传递 */
    reduxState?: StatePagingType<T>
    /**
     * 执行页面数据刷新请求的异步action,
     * 页面首次加载的时候初始化的页面数据根据redux.user中配置的默认值
     * 此参数必须和reduxState参数一起使用
     * */
    pageAsyncAction?: AsyncThunk<JsonResult<PagingResult<T>>, PagingData, AsyncThunkConfig>,
    // children?: React.ReactNode
    /** 表格工具栏搜索按钮的回调函数 */
    search?: (value: string) => void,
    /** 需要操作的redux仓库的名字 */
    storeName: StoreKeys
}

const log = LogFactory.getLogger("TableEnhance");
/** table增强组件 */
function TableEnhance<T extends BaseEntity>(props: TableEnhanceProps<T>) {
    const { pageAsyncAction, storeName } = props;
    const reduxState = useAppSelector(state => state[props.storeName]);
    const dispatch = useAppDispatch();
    const { message } = App.useApp();

    let pagination: TablePaginationConfig = {};
    if (reduxState) {
        pagination.pageSize = reduxState.pageSize;
        pagination.current = reduxState.currentPage;
        pagination.total = reduxState.total;
        if (pageAsyncAction) {
            pagination.onChange = (page: number, pageSize: number) => {
                log.trace("用户切换分页", page, pageSize);
                dispatch(pageAsyncAction({ page, pageSize }));
            };
            if (reduxState.requestStatus === RequestStatus.INIT) {
                // log.debug("执行初始化的异步action");
                dispatch(pageAsyncAction({ page: reduxState.currentPage, pageSize: reduxState.pageSize }));
            }
            if (reduxState.requestStatus === RequestStatus.REFRESH) {
                log.debug("请求刷新页面数据");
                setTimeout(() => {
                    dispatch(pageAsyncAction({ page: reduxState.currentPage, pageSize: reduxState.pageSize }));
                }, 0);
            }
        }
    }
    /** 刷新按钮回调 */
    const refresh = async () => {
        if (props.refresh) {
            await props.refresh();
        } else {
            if (reduxState && pageAsyncAction) {
               await dispatch(pageAsyncAction({ page: reduxState.currentPage, pageSize: reduxState.pageSize }));
               message.success("刷新成功");
            }
        }
    };
    return (
        <Card
            style={{ overflow: "hidden" }}
            title={props.title} extra={<Link to={props.backupUrl ?? ".."}>{props.backupText ?? "backup"}</Link>}>
            <TableToolbar info={reduxState.total} refresh={refresh} addUrl={props.addUrl} search={props.search} />
            <Table<T>
                // caption={props.title}
                scroll={{ x: 1000 }}
                columns={props.columns}
                dataSource={reduxState ? reduxState.data : props.dataSource}
                loading={reduxState ? reduxState.loading : props.loading}
                pagination={reduxState ? pagination : false}
            />
        </Card>
    );
}

export default TableEnhance;